// page/cart/order.js
var util = require ("../../util/util.js")
var animation
const startHours = []
const endHours = []
var d = new Date();
var h = d.getHours()
var i = parseInt((h + 2) / 2) * 2;
  i<8?i=8:i
for ( i ; i <= 22; i += 2) {
  startHours.push(i + ":00" + '-' +( i + 2) + ":00" )
  if (i == 10) {
    startHours.push('上午')
  }
  if (i == 16) {
    startHours.push('下午')
  }
  if (i == 18) {
    startHours.push('晚上')
  }
   if (i == 22) {
    startHours.push('不限时间')
  }
}
// for (let i = 10; i <= 24; i+=2) {
//   endHours.push(i + ":00")
// }
Page({
  data: {
    isHide: 0,
    hasAddr: false, 
    carts: [],               // 购物车列表
    totalPrice: 0,           // 总价，初始为0
    userInfo: [],            //收货人信息
    date: "",                //当前日期
    interval: "",                //配送区间
    cal:[],
    heka:'',
    info: '',
    coupons: '0',
    coupons_id: '',
    coupons_price: 0,
    startDate: util.formatDate(new Date),    //开始日期
    endDate: util.formatDateAfter(new Date),    //结束日期
    startTime: startHours,
    endTime: endHours,
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0],
    showhide: false,
    timeInfo: "" ,
    tx:'',
    mor:''

  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    var tx = options.tx ? options.tx : ''
    var mor = options.mor > 0 ? options.mor : 0
    
      this.setData({
        tx:options.tx ? options.tx : '',
        mor: options.mor > 0 ? options.mor : 0
      })
   
    var uid = wx.getStorageSync('uid');
    var app = getApp()
    var that = this;
  
      wx.request({
        url: app.globalData.host + '&g=App&m=Cart&a=orders', //仅为示例，并非真实的接口地址
        data: { tx: tx, mor: mor, gid: options.id ? options.id : 'all', uid: uid},
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          that.setData({
            carts: res.data.g,
            userInfo: res.data.d,
            info: res.data.a['real_name'] + res.data.a['mobile'],
            cal:  options.id ? options.id : 'all',
            coupons: res.data.s,
            isHide: 1,
          })
          // console.log(that.data.userInfo.length)
          // console.log(that.data.userInfo)
          if (that.data.userInfo != null) {
           
            that.setData({
              hasAddr: true
            })
          }
          that.getTotalPrice();
        }
      });
   

      // 初始化动画变量
      var animation = wx.createAnimation({
        duration: 500,
        transformOrigin: "50% 50%",
        timingFunction: 'ease',
      })
      this.animation = animation;         
    
    // console.log(this.data.startDate)
    
  },
  onShow:function(){


    // wx.showToast({
    //   title: '订单金额不能为空',
    //   duration: 2000,
    //   complete: function (res) {
    //     setTimeout(function () {
    //       that.setData({
    //         payStatus: 1
    //       })
    //     }, 2000)
    //   }
    // })
    var app = getApp()
    var that = this;
    var addressid = wx.getStorageSync('addressid');
    if (addressid){
      wx.request({
        url: app.globalData.host + '&g=App&m=Cart&a=hqaddress', //仅为示例，并非真实的接口地址
        data: { id: addressid },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          that.setData({
            userInfo: res.data.d,
              hasAddr: true
          })
          wx.removeStorageSync('addressid')
          that.getTotalPrice();
        }
      });
    }
  },
  neworder: function (){
    var price = this.data.totalPrice 
   
    if (price<=0){
       wx.showToast({
      title: '订单金额不能为空',
      duration: 2000,
      complete: function (res) {
        setTimeout(function () {
          that.setData({
            payStatus: 1
          })
        }, 2000)
      }
    })
    }else{
      var app = getApp()
      var that = this;
      var cal = that.data.cal;
      var date = that.data.date;
      var heka = that.data.heka;
      var tx = that.data.tx
      var mor = that.data.mor
      var interval = this.data.timeInfo 
      var coupons_id = that.data.coupons_id;
      var coupons_price = that.data.coupons_price;
      var uid = wx.getStorageSync('uid');
      // console.log(cal);
      wx.request({
        url: app.globalData.host + '&g=App&m=Cart&a=neworder', //仅为示例，并非真实的接口地址
        data: { tx: tx, mor: mor,gid: cal, uid: uid, date: date, heka: heka, coupons_id: coupons_id, coupons_price: coupons_price, interval: interval},
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)    
          if(res.data.code==1){
            wx.setStorageSync('order_sn', res.data.order_sn) // 存储
            wx.setStorageSync('sum', res.data.sum) // 存储
            wx.redirectTo({
              url: '/page/cart/payment'
            })
          }else{
            wx.showToast({
              title: res.data.msg,
              duration: 2000,
            
            })
          }
          
        }
      });
    }
   
      
  },
  /**
   * 计算总价
   */
  getTotalPrice() {
      let carts = this.data.carts;                  // 获取购物车列表
      if (carts==null){
        return false
      }
      let total = 0;
      for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
          //  if (carts[i].selected) {                     // 判断选中才会计算价格
          total += carts[i].num * carts[i].price;   // 所有价格加起来
          //  }
      }
      this.setData({                                // 最后赋值到data中渲染到页面
          carts: carts,
          totalPrice: total.toFixed(2)
      });
  },

  bindDateChange: function (e) {
      this.setData({
          date: e.detail.value
      })
      this.openPop()
  }, 
  // 点击所在地区弹出选择框
  selectTime: function (e) {
    var that = this
   

    if (!that.data.date){
      wx.showToast({
        title: '请先选择到达日期！',
        duration: 2000,
        complete: function (res) {
          setTimeout(function () {
          }, 2000)
        }
      })
      return false
    }//判断日期是不是今天
    if (that.data.startDate == that.data.date){ //是今天
    console.log(1)
      const startHours = []
      var d = new Date();
      var h = d.getHours()
      var i = parseInt((h + 2) / 2) * 2;
      i < 8 ? i = 8 : i
      for (i; i <= 22; i += 2) {
        startHours.push(i + ":00" + '-' + (i + 2) + ":00")
        if (i == 10) {
          startHours.push('上午')
        }
        if (i == 16) {
          startHours.push('下午')
        }
        if (i == 22) {
          startHours.push('晚上')
        }
        if (i == 22) {
          startHours.push('不限时间')
        }
      }
      this.setData({
        startTime: startHours
      })
    }else{
      console.log(1)
      const startHours = []
      for (var i=8; i <= 22; i += 2) {
        startHours.push(i + ":00" + '-' + (i + 2) + ":00")
        if (i == 10) {
          startHours.push('上午')
        }
        if (i == 16) {
          startHours.push('下午')
        }
        if (i == 18) {
          startHours.push('晚上')
        }
        if (i == 22) {
          startHours.push('不限时间')
        }
      }
      this.setData({
        startTime: startHours
      })
    }
    if (that.data.addressMenuIsShow) {
      return
    }
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    var that = this
    if (isShow) {
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(40 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  timeCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  timeSure: function (e) {
    var that = this
    var value = that.data.value
    that.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var timeInfo = that.data.startTime[value[0]]       /*+ ' - ' + that.data.endTime[value[1]]*/
    that.setData({
      interval: timeInfo+'（节假日当日送到）',
    })
  },
  hideTimeSelected: function (e) {
    this.startAddressAnimation(false)
  },
  // 处理省市县联动逻辑
  timeChange: function (e) {
    var value = e.detail.value
    var startTime = this.data.startTime
    var endTime = this.data.endTime
    var startTimeNum = value[0]
    var endTimeNum = value[1]
    var newH = []
    for (let i = 2*(parseInt(value) + 5); i <= 24; i+=2) {
      newH.push(i + ":00")
    }
    if (this.data.value[0] != startTimeNum) {
      this.setData({
        value: [startTimeNum, 0],
        endTime: newH
      })
    } else if (this.data.value[1] != endTimeNum) {
      this.setData({
        value: [startTimeNum, endTimeNum]
      })
    } else {
      this.setData({
        value: [startTimeNum, endTimeNum]
      })
    }
  },    
  openPop: function () {
    var that = this
    if (!that.data.date) {
      wx.showToast({
        title: '请先选择到达日期！',
        duration: 2000,
        complete: function (res) {
          setTimeout(function () {
          }, 2000)
        }
      })
      return false
    }//判断日期是不是今天
    if (that.data.startDate == that.data.date) { //是今天
      console.log(1)
      const startHours = []
      var d = new Date();
      var h = d.getHours()
      var i = parseInt((h + 2) / 2) * 2;
      i < 8 ? i = 8 : i
      startHours.push('不限时间')
      for (i; i <= 22; i += 2) {
        startHours.push(i + ":00" + '-' + (i + 2) + ":00")
        if (i == 10) {
          startHours.push('上午')
        }
        if (i == 16) {
          startHours.push('下午')
        }
        if (i == 22) {
          startHours.push('晚上')
        }
        
      }
      that.setData({
        startTime: startHours
      })
    } else {
      console.log(2)
      const startHours = []
      for (var i = 8; i <= 22; i += 2) {
        startHours.push(i + ":00" + '-' + (i + 2) + ":00")
        if (i == 10) {
          startHours.push('上午')
        }
        if (i == 16) {
          startHours.push('下午')
        }
        if (i == 18) {
          startHours.push('晚上')
        }
        if (i == 22) {
          startHours.push('不限时间')
        }
      }
      that.setData({
        startTime: startHours
      })
    }
    that.setData({
      showhide: true
    })
  },
  closePop: function () {
    this.setData({
      showhide: false
    })
  },
  selected: function (e) {
    var index = e.currentTarget.dataset.id
    this.setData({
      timeInfo: this.data.startTime[index] +'（节假日当日送到）',
      showhide: false
    })
  }
})